<div class="diskoverview">
    <style>
        #diskrender{
            max-height: 300px;
            overflow-y: auto;
            overflow-x: hidden;
        }

        #diskrender .ui.avatar.image{
            border-radius: 0 !important;
            margin-top: 1em;
        }

        #diskrender .content{
            width: calc(100% - 40px);
        }
        
        #diskrender .driveinfo:hover{
           border-radius: 6px;
        }

        #diskrender .diskspace{
            margin-top: 0.6em;
        }

        #diskrender .progress .bar:not(.raiddev){
            background-color: rgb(82, 201, 255);
        }

        #diskrender .progress .bar.lowspace{
            background-color: #b51d1d !important;
        }

        #diskrender .progress .bar.raiddev.failing{
            background-color: #f5ef42 !important;
        }

        #diskrender .progress .bar.raiddev.healthy{
            background-color: #5cd858 !important;
        }

        #diskrender .progress .bar .progress{
            background-color: transparent !important;
        }

        #diskrender .raidVolStateIcon{
            position: absolute;
            left: 2.0em;
            top: 2.5em;
            background: white;
            border-radius: 50%;
            width: 1.2em;
        }
        
        #diskrender .inactive.driveinfo{
            opacity: 0.5;
        }

        #refreshDiskRenderBtn{
            float: right;
        }
    </style>
    <div id="diskrender">
        <div class="ui list" id="diskspaceList">
            
        </div>
        <div class="ui list" id="raidVolList">
            
        </div>
    </div>

    <script>
        // This is intented to be loaded on the desktop.system interface
        // use paths from web root instead of relative path from this script

        updateDiskSpaceOverview();
        function updateDiskSpaceOverview(){
            $("#diskspaceList").html(`<div style="text-align: center; margin-top: 2em;"><i class="ui loading spinner icon"></i></div>`);
            $.ajax({
                url: "./system/disk/diskmg/view", 
                success: function(data){
                    if (data.error != undefined){
                        //Unable to load API, hide the util
                        $("#diskrender").hide();
                        return;
                    }
                    if (data[0] && typeof(data[0]["blockdevices"]) != "undefined"){
                        //This is a linux host
                        $("#diskspaceList").html("");
                        for (var i = 0; i < data[0]["blockdevices"].length; i++){
                            let thisDiskInfo = data[0]["blockdevices"][i];
                            let driveId = thisDiskInfo.name;
                            let diskName = "";
                            let isRaid = false;

                            if (thisDiskInfo.children == null){
                                //This is a disk that is not formated or damaged
                                continue;
                            }

                            console.log(data[1]["blockdevices"][i]);
                            if (data[1]["blockdevices"][i].fstype == "linux_raid_member"){
                                //RAID source partition / drive
                                continue; //Remove this line to also render RAID disk
                                isRaid = true;
                            }

                            if (thisDiskInfo.children.length > 0){
                                //Try to extract mountpoint as name
                                let mountpoint = thisDiskInfo.children[0].mountpoint;
                                if (mountpoint == null || mountpoint == undefined || mountpoint == ""){
                                    //Not mounted via arozos. Try to get the mountpoint from other partitions
                                    if (thisDiskInfo.children.length > 1){
                                        //Multiple partitions, combine them into /dev/sdX(1+2+3)
                                        mountpoint = "/dev/" + thisDiskInfo.children[0].name;
                                        mountpoint = mountpoint.replace(/[0-9]/g, ""); //Remove the partition number
                                        mountpoint += "[";
                                        for (var j = 0; j < thisDiskInfo.children.length; j++){
                                            let partitionNumber = thisDiskInfo.children[j].name.replace(/[a-zA-Z]/g, "");
                                            mountpoint += partitionNumber + "+";
                                        }
                                        mountpoint = mountpoint.slice(0, -1); //Remove the last +
                                        mountpoint += "]";
                                    }else{
                                        //Single partition
                                        mountpoint = "/dev/"  + thisDiskInfo.children[0].name;
                                    }
                                }

                                diskName = mountpoint;
                            }

                            let remainingSpace = 0;
                            let totalSpace = thisDiskInfo.size;
                            //Try to get the remaining space from mounted partitions
                            if (data[2].length > 0){
                                let accumulateTotalSpace = 0;
                                let accumulateRemainingSpace = 0;
                                for (var j = 0; j < data[2].length; j++){
                                    //For each mounted partitions
                                    let thisPartInfo = data[2][j];
                                    let thisPartName = thisPartInfo[0]; //e.g. /dev/sdc1
                                    if (thisPartName.includes("/" + driveId)){
                                        //Check if part name include drive id, e.g. /sdc
                                        //If yes, add the parition remaining space to acc
                                        accumulateRemainingSpace += thisPartInfo[3];
                                        accumulateTotalSpace += thisPartInfo[1];
                                    }
                                }

                                remainingSpace = accumulateRemainingSpace;
                                totalSpace = accumulateTotalSpace;
                            }
                            
                            let usedSpace = totalSpace - remainingSpace;
                            let usedPercentage = (usedSpace / totalSpace) * 100;
                            let colorClass = "";
                            if (usedPercentage > 90){
                                colorClass = "lowspace";
                            }

                            if (usedPercentage >= 100){
                                //Prevent overflow
                                usedPercentage = 100;
                            }

                            //Check if raid. As raid is controlled by mdadm, we don't know how much storage it has
                            if (isRaid){
                                usedPercentage = 100;
                                colorClass = "raiddev";
                                diskName = "[RAID Disk]"
                            }

                            $("#diskspaceList").append(`<div class="item driveinfo">
                                <img class="ui avatar image" src="img/system/drive.svg">
                                <div class="content">
                                    <div class="header">${diskName} (${driveId})
                                        <span style="float: right;font-size: 0.85em;">${usedPercentage.toFixed(1)}% | ${ao_module_utils.formatBytes(thisDiskInfo.size, 1)}</span>    
                                    </div>
                                    <div class="description">
                                        <div class="ui active small fluid progress diskspace">
                                            <div class="bar ${colorClass}" style="width: ${usedPercentage}%">
                                            <div class="progress"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                </div>`);
                        }
                    }else if (data[0].length == 7){
                        //This is a Window hosts
                        $("#diskspaceList").html("");
                        for (var i = 0; i < data.length; i++){
                            let thisDiskInfo = data[i];
                            if (thisDiskInfo.length < 6){
                                //Not a HDD
                                continue;
                            }
                            let driveId = thisDiskInfo[0].replace("\\\\", "\\");
                            let diskName = thisDiskInfo[2];
                            let remainingSpace = thisDiskInfo[5];
                            let totalSpace = thisDiskInfo[6];
                            let usedSpace = totalSpace - remainingSpace;
                            let usedPercentage = (usedSpace / totalSpace) * 100;
                            let colorClass = "";
                            if (usedPercentage > 90){
                                colorClass = "lowspace";
                            }

                            if (usedPercentage >= 100){
                                //Prevent overflow
                                usedPercentage = 100;
                            }

                            $("#diskspaceList").append(`<div class="item driveinfo">
                                <img class="ui avatar image" src="img/system/drive.svg">
                                <div class="content">
                                    <div class="header">
                                        ${diskName} (${driveId})
                                        <span style="float: right;font-size: 0.85em;">${usedPercentage.toFixed(1)}% | ${ao_module_utils.formatBytes(totalSpace, 1)}</span>
                                    </div>
                                    <div class="description">
                                        <div class="ui active small fluid progress diskspace">
                                            <div class="bar ${colorClass}" style="width: ${usedPercentage}%">
                                            <div class="progress"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                </div>`);
                        }
                    }else{
                        //Something else
                        $("#diskrender").text("Platform not supported");
                    }

                    //Update themecolor, see desktop.system setThemeColor();
                    $("#diskrender .progress .bar").css({
                        "background-color": desktopThemeColor
                    });

                    updateRAIDVolumeOverview();
                }, error: function(){
                    $("#diskspaceList").html(`<div style="text-align: center; margin-top: 1em; height: 2em;"><i class="ui red ban icon"></i><i class="ui grey hdd icon"></i></div>`);
                }
            });
        }

        function updateRAIDVolumeOverview(){
            $("#raidVolList").html("");
            $.ajax({
                url: "/system/disk/raid/overview",
                method: "GET",
                success: function(data){
                    if (data.error != undefined){
                        //Hide the section
                        $("#raidVolList").hide();
                    }else{
                        //Render the data
                        $("#raidVolList").show();
                        let containUnhealthy = false;
                        data.forEach(raidinfo => {
                            let usedPercentage = (raidinfo.UsedSize / raidinfo.TotalSize) * 100;
                            let colorClass = "raiddev healthy";
                            if (!raidinfo.IsHealthy){
                                colorClass = "raiddev failing";
                                containUnhealthy = true;
                            }

                            let activeClass = ""
                            if (!raidinfo.Status.includes("active")){
                                activeClass = "inactive";
                            }

                            $("#raidVolList").append(`<div class="item ${activeClass} driveinfo">
                                <img class="ui avatar image" src="img/system/cluster.svg">
                                <div class="content">
                                    <div class="header">${raidinfo.Name} (${raidinfo.Level.toUpperCase()} | ${raidinfo.Status})
                                        <span style="float: right;font-size: 0.85em;">${usedPercentage.toFixed(1)}% | ${ao_module_utils.formatBytes(raidinfo.TotalSize, 1)}</span>    
                                    </div>
                                    <div class="description">
                                        <div class="ui active small fluid progress diskspace">
                                            <div class="bar ${colorClass}" style="width: ${usedPercentage}%">
                                            <div class="progress"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <span class="raidVolStateIcon">${raidinfo.IsHealthy?'<i class="ui green check circle icon"></i>':'<i class="ui red times circle icon"></i>'}</span>
                                </div>`);
                        });
                        
                        if (data.length == 0){
                            //No raid devices
                        }

                        if (containUnhealthy){
                            //Set require attension
                            setTimeout(function(){
                                updateSystemOverviewStatusText(1);
                            }, 1000);
                        }
                    }
                },
                error: function(){
                    //Unknown error, hide raid vol list
                    $("#raidVolList").hide();
                }
            });
        }

        //Update the overview every 15 minutes
        setInterval(function(){
            updateDiskSpaceOverview();
        }, 900 * 1000);
    </script>
</div>